package com.bolt.support.sqlconfig.builder;

import com.bolt.convention.exception.ServiceException;
import com.bolt.support.sqlconfig.base.SQLConfiguration;
import com.bolt.support.sqlconfig.base.SqlStatement;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.InputStreamReader;


public class SqlTemplateFactory implements InitializingBean, DisposableBean {

    private final SQLConfiguration configuration;

    private Resource[] sqlMapperLocations;

    public SqlTemplateFactory() {
        configuration = new SQLConfiguration();
    }

    public void init() {
        try {
            if (this.sqlMapperLocations != null) {
                for (int i = 0; i < this.sqlMapperLocations.length; i++) {
                    XmlSqlConfigBuilder xml = new XmlSqlConfigBuilder(new InputStreamReader(sqlMapperLocations[i].getInputStream(), "UTF-8"), configuration);
                    xml.parse();
                }
            }
        } catch (Exception e) {
            throw new ServiceException(e);
        }

    }

    public SQLConfiguration getConfiguration() {
        return configuration;
    }

    public SqlStatement find(String key) {
        SqlStatement statement = configuration.getMappedStatement(key);
        if (statement == null) {
            throw new ServiceException("Unknown sql <" + key + "> in SQL XML.");
        }
        return statement;
    }




    public Resource[] getSqlMapperLocations() {
        return sqlMapperLocations;
    }

    public void setSqlMapperLocations(Resource[] sqlMapperLocations) {
        this.sqlMapperLocations = sqlMapperLocations;
    }

    public void setSqlMapperFilePath(String... configLocations) {
        this.sqlMapperLocations = new Resource[configLocations.length];
        for (int i = 0; i < configLocations.length; i++) {
            this.sqlMapperLocations[i] = new ClassPathResource(configLocations[i].trim());
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    @Override
    public void destroy() throws Exception {
        configuration.clean();
    }

    public void reload() {
        configuration.clean();
        init();
    }


}
